package com.dayuanit.dy15.atm.service.impl;

import com.dayuanit.dy15.atm.dto.UserDetailDTO;
import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.entity.UserDetail;
import com.dayuanit.dy15.atm.enums.EmailStatusEnum;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.mapper.UserDetailMapper;
import com.dayuanit.dy15.atm.mapper.UserMapper;
import com.dayuanit.dy15.atm.service.UserDetailService;
import com.dayuanit.dy15.atm.util.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserDetailServiceImpl implements UserDetailService {

    @Autowired
    private UserDetailMapper userDetailMapper;

    @Autowired
    private MD5Utils md5Utils;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindEmail(long userId, String email) {
        // 校验  邮箱是否绑定

        //查询此邮箱是否被绑定 在detail表的user_id字段加唯一索引 保证在并发情况下有用户详情记录只有一条
        //TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
        UserDetail userDetail = userDetailMapper.getByEmail(email, EmailStatusEnum.activate.getK());
        if (userDetail != null) {
            throw new BizException("邮箱已经被绑定");
        }

        // 添加一条记录 或者修改一条记录
        UserDetail myUserDetail = userDetailMapper.getByUserIdEmail(userId, email);
        if (null != myUserDetail) {
            myUserDetail.setModifyTime(new Date());
            userDetailMapper.updateByPrimaryKeySelective(myUserDetail);
            return;
        }

        //如果未绑定此邮箱 则新增一条记录
        userDetail = new UserDetail();
        userDetail.setEmail(email);
        userDetail.setStatus(EmailStatusEnum.un_activate.getK());
        userDetail.setModifyTime(new Date());
        userDetail.setUserId(userId);
        userDetail.setCreateTime(new Date());

        userDetailMapper.insert(userDetail);
    }


    @Override
    public void activeEmail(String email, long expireTime, String sign, long userId) {

        if (System.currentTimeMillis() > expireTime) {
            throw new BizException("激活连接已失效");
        }

        String tempSign = md5Utils.emailActiveUrl(email, expireTime);
        if (!tempSign.equals(sign)) {
            throw new BizException("激活失败");
        }

        //将邮箱激活
        UserDetail userDetail = userDetailMapper.getByUserIdEmail(userId, email);
        if (null == userDetail) {
            throw new BizException("激活失败");
        }

        if (userDetail.getStatus() == EmailStatusEnum.activate.getK()) {
            return;
        }

        int rows = userDetailMapper.updateStatus(userDetail.getId(), userDetail.getStatus(), EmailStatusEnum.activate.getK());
        if (1 != rows) {
            throw new BizException("激活失败");
        }
    }

    @Override
    public UserDetailDTO loadEmail(long userId) {
        UserDetail userDetail = userDetailMapper.getByUserId(userId);
        if (null == userDetail) {
            throw new BizException("你还没绑定邮箱");
        }
        return new UserDetailDTO(userDetail.getEmail(), userDetail.getStatus());
    }

    @Override
    public void unBindEmail(long userId) {
        UserDetail userDetail = userDetailMapper.getByUserId(userId);
        if (null == userDetail) {
            throw new BizException("你还木有绑定邮箱");
        }

        if (userDetail.getStatus() != EmailStatusEnum.activate.getK()) {
            return;
        }

        int rows = userDetailMapper.updateStatus(userDetail.getId(), userDetail.getStatus(), EmailStatusEnum.un_bind.getK());
        if (1 != rows) {
            throw new BizException("解绑失败");
        }

    }

    @Override
    public void retrievePwd(String email, long expireTime, String sign, String password, String confirmPwd) {
        if (System.currentTimeMillis() > expireTime) {
            throw new BizException("找回密码失败");
        }

        //校验签名
        String tempSign = md5Utils.emailActiveUrl(email, expireTime);
        if (!tempSign.equals(sign)) {
            throw new BizException("找回密码失败");
        }

        if (StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmPwd)) {
            throw new BizException("请输入必填参数");
        }

        if (!confirmPwd.equals(password)) {
            throw new BizException("两次输入的密码不相等");
        }

        UserDetail userDetail = userDetailMapper.getByEmail(email, EmailStatusEnum.activate.getK());
        if (null == userDetail) {
            throw new BizException("找回密码失败");
        }

        User user = userMapper.selectByPrimaryKey(userDetail.getUserId());
        user.setPassword(md5Utils.userPassword(password, user.getUsername()));

        int rows = userMapper.updatePwd(user.getId(), user.getPassword());
    }
}
